#!/bin/bash
mysql_configuration_file_path="/home/zxhtom/temp/mysql/my.cnf"
mysql_runtime_log_path="/home/zxhtom/temp/mysql/mysqld.log"
mysql_configuration_file_path="/etc/my.cnf"
mysql_runtime_log_path="/var/log/mysqld.log"
HOSTNAME="127.0.0.1"
PORT=3306
MYSQL_USER=yapai
MYSQL_PASSWORD=ypkj@1234
MYSQL_ROOT_PASSWORD=APkj@1234

currentHome=$(cd "$(dirname "$0")";pwd)
YAPAI_HOME=$(dirname "$currentHome")

if [ ! -d ${HOME}/zxhtom ]
then
  mkdir -p ${HOME}/zxhtom
fi
# remove
for i in $(rpm -qa|grep mysql);
do 
  echo "delete $i"
  sudo rpm -e $i --nodeps;
done
for i in $(rpm -qa|grep mariadb);
do 
  echo "delete $i"
  sudo rpm -e $i --nodeps;
done
sudo rm -rf /var/lib/mysql && rm -rf /etc/my.cnf

mysql_file=`ls ${currentHome} | grep mysql | grep bundle | grep tar`

rm -rf ${HOME}/zxhtom/*
if [[ ! -d ${HOME}/zxhtom ]]
then
  mkdir -p ${HOME}/zxhtom
fi
if [[ -d ${currentHome}/zxhtom ]]
then
  cp -rvf ${currentHome}/zxhtom/* ${HOME}/zxhtom/
fi
tar -xvf ${currentHome}/${mysql_file} -C ${HOME}/zxhtom/
# install mysql server

# install in order
order_rpm_files=("mysql-community-common" "mysql-community-client-plugins" "mysql-community-libs" "mysql-community-client" "mysql-community-icu-data-files" "mysql-community-server")
# rpm -ivh mysql-community-common-8.0.26-1.el7.x86_64.rpm
# rpm -ivh mysql-community-client-plugins-8.0.26-1.el7.x86_64.rpm
# rpm -ivh mysql-community-libs-8.0.26-1.el7.x86_64.rpm
# rpm -ivh mysql-community-client-8.0.26-1.el7.x86_64.rpm
# rpm -ivh mysql-community-server-8.0.16-2.el7.x86_64.rpm
for rpm_file in ${order_rpm_files[@]}
do
  real_rpm_file=`ls ${HOME}/zxhtom | grep -E ''"${rpm_file}"'-[0-9]{1}\.'`
  sudo rpm -ivh ${HOME}/zxhtom/${real_rpm_file}
done

# append config to configuration
# default_authentication_plugin=mysql_native_password
# lower_case_table_names=1
sudo cp -rvf ${currentHome}/conf/my.cnf ${mysql_configuration_file_path}
# sudo sed -i '$adefault_authentication_plugin=mysql_native_password' ${mysql_configuration_file_path}
# sudo sed -i '$alower_case_table_names=1' ${mysql_configuration_file_path}

sudo systemctl restart mysqld

# select defalut password

default_root_password=`sudo cat ${mysql_runtime_log_path} | grep -E 'A temporary password is generated for root@localhost' | sed -n '$p' | awk -F 'root@localhost:' '{print $NF}'`
default_root_password=$(echo $default_root_password)
echo "@@"${default_root_password}
# update root password , wait 15s
echo "will sleep wait 15s...."
sleep 15s
mysqladmin -uroot -p''"${default_root_password}"'' password ''"${MYSQL_ROOT_PASSWORD}"''
# mysql -hlocalhost -uroot -p${default_root_password} -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${MYSQL_ROOT_PASSWORD}';flush privileges;" 

mysql -hlocalhost -uroot -p${MYSQL_ROOT_PASSWORD} -e "set global validate_password.policy=LOW;" 
mysql -hlocalhost -uroot -p${MYSQL_ROOT_PASSWORD} -e "create user 'yapai'@'%' identified by '${MYSQL_PASSWORD}';grant all on *.* to 'yapai'@'%';flush privileges;" 


# init business tables

dbs=("nacos" "mingjingtai" "nanshan" "service_center" "shuiliandong" "unified_index_platform" "wechat" "workflow" "wuxingshan" "logaudit" "hvac" "version_manage" "operation")
for DBNAME in "${dbs[@]}"
do
  mysql -h ${HOSTNAME} -u root -p${MYSQL_ROOT_PASSWORD} -e "DROP DATABASE IF EXISTS ${DBNAME}; CREATE DATABASE ${DBNAME} CHARACTER SET 'utf8mb4';grant all privileges 
  on ${DBNAME}.* to ${MYSQL_USER}@'%';flush privileges;"  --connect-expired-password
done


SQLLIST=`ls  $currentHome"/architecture"`
for FILENAME in ${SQLLIST[@]}
do
   DBNAME=${FILENAME::-4}
   echo "DBNAME IS "$DBNAME
   create_table_data="use ${DBNAME};source ${currentHome}/architecture/${DBNAME}.sql;"
   mysql -h${HOSTNAME}  -P${PORT}  -u${MYSQL_USER} -p${MYSQL_PASSWORD} -e"${create_table_data}"
done

# restart all services
ypstart -r 1

# reset to start of 2023
for DBNAME in "${dbs[@]}"
do
  mysql -hlocalhost -uyapai -p${MYSQL_PASSWORD} -e 'update '"${DBNAME}"'.global set v=20230101;'
done

for database in `ls ${currentHome}/append`
do
  for table in `ls ${currentHome}/append/${database}`
  do
    mysql -hlocalhost -uyapai -p${MYSQL_PASSWORD} -D${database}<${currentHome}/append/${database}/${table}
  done
done
# restart all services again
ypstart -r 1

HASH=`curl http://localhost:8700/sld/random/getReadomMd5 | sed -ne 's/{"//p' |sed -ne's/"}//p'| awk -F "[ \" ]+" '{print $NF}'`
echo "获取的服务授权密钥:"${HASH}
# openssl md5
SHOWPASS="123456"
# PASS=`printf  ${SHOWPASS} | openssl md5 | awk '{print $NF}'`
PASS=`mysql -hlocalhost -uyapai -p${MYSQL_PASSWORD} -e "use shuiliandong; select * from t_sys_user where user_name='ypkj'\G" 2>&1 | sed -n '2,$p' | grep -E 'password' | awk -F ':' '{print $2}'`
LP=`printf  ${PASS}${HASH}|openssl md5 | awk '{print $NF}'`
TOKENMSG=`curl -X POST "http://localhost:8700/sld/oauth/token?username=ypkj&password=${LP}&grant_type=password&client_id=Auth&client_secret=user123"`
TOKEN=`echo ${TOKENMSG} | grep -oE 'access_token":"[0-9a-zA-Z_.\-]+' | awk -F "[:\"]+" '{print $2}'`
#TOKEN=`echo ${TOKENMSG} | grep -E 'access_token":"[0-9a-zA-Z]+'`
LAST_TOKEN="Bearer "${TOKEN}
max_count=999999
assets=("assetssystem" "assetstype" "assets" "dept" "location")
for item in ${assets[@]}
do
  total=`curl -H 'Authorization:'"${LAST_TOKEN}"'' 'http://localhost:8080/api/tenant/assetInfos?pageSize='"${max_count}"'&page=0&sortProperty=createdTime&sortOrder=DESC&type='"${item}"'' | jq .totalElements`
  if [ $total -gt 999999 ]
  then
    echo $item"need delete by handler"
  fi

  ddd=`curl -H 'Authorization:'"${LAST_TOKEN}"'' 'http://localhost:8080/api/tenant/assetInfos?pageSize='"${max_count}"'&page=0&sortProperty=createdTime&sortOrder=DESC&type='"${item}"'' | jq .data | jq '.[].id.id '`
  for data in ${ddd[@]}
  do
    echo ${data:1:-1}
    curl -XDELETE -H 'Authorization:'"${LAST_TOKEN}"'' 'http://localhost:8080/api/asset/'"${data:1:-1}"''
  done
done
mysql -hlocalhost -uyapai -p${MYSQL_PASSWORD} -e"use shuiliandong;delete from t_relatin_thingboard;use nanshan;delete from t_relatin_thingboard;"
